<template>
  <div class="cleaning-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>卫生管理</span>
          <div class="button-group">
            <el-button type="primary" @click="handleAddTask" class="add-button">
              <el-icon-plus /> 添加清洁任务
            </el-button>
            <el-button type="success" @click="handleAddInspection" class="add-button">
              <el-icon-plus /> 添加卫生检查
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="清洁任务管理">
          <div class="search-container">
            <el-input v-model="taskSearchQuery" placeholder="请输入房间号、清洁类型或状态" prefix-icon="Search"
              class="search-input" />
            <el-button type="primary" @click="handleTaskSearch">搜索</el-button>
          </div>

          <div class="table-container">
            <el-table v-loading="taskLoading" :data="taskList" style="width: 100%" max-width="100%"
              class="custom-table-class">
              <el-table-column prop="id" label="任务ID" width="80" />
              <el-table-column prop="roomNumber" label="房间号" width="100" />
              <el-table-column prop="taskType" label="清洁类型" />
              <el-table-column prop="scheduledDate" label="计划日期" width="150" />
              <el-table-column prop="cleaner" label="保洁人员" width="120" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status === '待清洁' ? 'warning' : scope.row.status === '进行中' ? 'primary' : 'success'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="completionTime" label="完成时间" width="150" />
              <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleViewTaskDetail(scope.row)">查看详情</el-button>
                  <el-button size="small" type="primary" @click="handleEditTask(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteTask(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination v-model:current-page="taskCurrentPage" v-model:page-size="taskPageSize"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="taskTotal"
              @size-change="handleTaskSizeChange" @current-change="handleTaskCurrentChange" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="卫生检查管理">
          <div class="search-container">
            <el-input v-model="inspectionSearchQuery" placeholder="请输入房间号、检查类型或状态" prefix-icon="Search"
              class="search-input" />
            <el-button type="primary" @click="handleInspectionSearch">搜索</el-button>
          </div>

          <div class="table-container">
            <el-table v-loading="inspectionLoading" :data="inspectionList" style="width: 100%" max-width="100%">
              <el-table-column prop="id" label="检查ID" width="80" />
              <el-table-column prop="roomNumber" label="房间号" width="100" />
              <el-table-column prop="inspectionDate" label="检查日期" width="150" />
              <el-table-column prop="inspector" label="检查人员" width="120" />
              <el-table-column prop="score" label="评分" width="80">
                <template #default="scope">
                  <el-rate :value="scope.row.score / 2" disabled show-score />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '合格' ? 'success' : 'danger'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleViewInspectionDetail(scope.row)">查看详情</el-button>
                  <el-button size="small" type="primary" @click="handleEditInspection(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteInspection(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination v-model:current-page="inspectionCurrentPage" v-model:page-size="inspectionPageSize"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="inspectionTotal"
              @size-change="handleInspectionSizeChange" @current-change="handleInspectionCurrentChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑清洁任务对话框 -->
    <el-dialog v-model="taskDialogVisible" :title="taskDialogTitle" width="760px">
      <el-form :model="taskFormData" ref="taskFormRef" :rules="taskRules" label-width="150px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="taskFormData.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="清洁类型" prop="taskType">
          <el-select v-model="taskFormData.taskType" placeholder="请选择清洁类型">
            <el-option label="日常清洁" value="日常清洁" />
            <el-option label="深度清洁" value="深度清洁" />
            <el-option label="退租清洁" value="退租清洁" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期" prop="scheduledDate">
          <el-date-picker v-model="taskFormData.scheduledDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="保洁人员" prop="cleaner">
          <el-input v-model="taskFormData.cleaner" placeholder="请输入保洁人员姓名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="taskFormData.status" placeholder="请选择状态">
            <el-option label="待清洁" value="待清洁" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTaskSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑卫生检查对话框 -->
    <el-dialog v-model="inspectionDialogVisible" :title="inspectionDialogTitle" width="760px">
      <el-form :model="inspectionFormData" ref="inspectionFormRef" :rules="inspectionRules" label-width="150px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="inspectionFormData.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="检查日期" prop="inspectionDate">
          <el-date-picker v-model="inspectionFormData.inspectionDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="检查人员" prop="inspector">
          <el-input v-model="inspectionFormData.inspector" placeholder="请输入检查人员姓名" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-slider v-model="inspectionFormData.score" :min="0" :max="10" :step="0.5" show-stops />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="inspectionFormData.status" placeholder="请选择状态">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input v-model="inspectionFormData.description" type="textarea" placeholder="请输入问题描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="inspectionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleInspectionSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import cleaningService from '../../services/cleaningService.ts'

// 标签页相关
const activeTab = ref('0')

// 清洁任务相关
const taskSearchQuery = ref('')
const taskList = ref<any[]>([])
const taskLoading = ref(false)
const taskCurrentPage = ref(1)
const taskPageSize = ref(10)
const taskTotal = ref(0)
const taskDialogVisible = ref(false)
const taskDialogTitle = ref('添加清洁任务')
const taskFormData = reactive({
  id: '',
  roomNumber: '',
  taskType: '',
  scheduledDate: '',
  cleaner: '',
  status: '待清洁',
  completionTime: ''
})
const taskFormRef = ref<any>(null)
const taskRules = {
  roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  taskType: [{ required: true, message: '请选择清洁类型', trigger: 'change' }],
  scheduledDate: [{ required: true, message: '请选择计划日期', trigger: 'change' }],
  cleaner: [{ required: true, message: '请输入保洁人员姓名', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 卫生检查相关
const inspectionSearchQuery = ref('')
const inspectionList = ref<any[]>([])
const inspectionLoading = ref(false)
const inspectionCurrentPage = ref(1)
const inspectionPageSize = ref(10)
const inspectionTotal = ref(0)
const inspectionDialogVisible = ref(false)
const inspectionDialogTitle = ref('添加卫生检查')
const inspectionFormData = reactive({
  id: '',
  roomNumber: '',
  inspectionDate: '',
  inspector: '',
  score: 10,
  status: '合格',
  description: ''
})
const inspectionFormRef = ref<any>(null)
const inspectionRules = {
  roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  inspectionDate: [{ required: true, message: '请选择检查日期', trigger: 'change' }],
  inspector: [{ required: true, message: '请输入检查人员姓名', trigger: 'blur' }],
  score: [{ required: true, message: '请设置评分', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 生命周期钩子
onMounted(() => {
  fetchTaskList()
  fetchInspectionList()
})

// 获取清洁任务列表
const fetchTaskList = () => {
  taskLoading.value = true
  cleaningService.getCleaningList(taskCurrentPage.value, taskPageSize.value, taskSearchQuery.value).then((res: any) => {
    if (res.code === 200) {
      taskList.value = res.data
      taskTotal.value = res.total
      taskLoading.value = false
    }
  }).catch((error: any) => {
    console.error('获取清洁任务列表失败:', error)
    ElMessage.error('获取清洁任务列表失败')
    taskLoading.value = false
  })
}

// 获取卫生检查列表
const fetchInspectionList = () => {
  inspectionLoading.value = true
  cleaningService.getInspectionList(inspectionCurrentPage.value, inspectionPageSize.value, inspectionSearchQuery.value).then((res: any) => {
    if (res.code === 200) {
      inspectionList.value = res.data
      inspectionTotal.value = res.total
      inspectionLoading.value = false
    }
  }).catch((error: any) => {
    console.error('获取卫生检查列表失败:', error)
    ElMessage.error('获取卫生检查列表失败')
    inspectionLoading.value = false
  })
}

// 清洁任务搜索事件
const handleTaskSearch = () => {
  taskCurrentPage.value = 1
  fetchTaskList()
}

// 清洁任务分页事件
const handleTaskSizeChange = (size: number) => {
  taskPageSize.value = size
  fetchTaskList()
}

const handleTaskCurrentChange = (current: number) => {
  taskCurrentPage.value = current
  fetchTaskList()
}

// 添加清洁任务
const handleAddTask = () => {
  taskDialogTitle.value = '添加清洁任务'
  // 重置表单
  taskFormData.id = ''
  taskFormData.roomNumber = ''
  taskFormData.taskType = ''
  taskFormData.scheduledDate = ''
  taskFormData.cleaner = ''
  taskFormData.status = '待清洁'
  taskFormData.completionTime = ''
  if (taskFormRef.value) {
    taskFormRef.value.resetFields()
  }
  taskDialogVisible.value = true
}

// 编辑清洁任务
const handleEditTask = (row: any) => {
  taskDialogTitle.value = '编辑清洁任务'
  // 填充表单数据
  Object.assign(taskFormData, row)
  taskDialogVisible.value = true
}

// 查看清洁任务详情
const handleViewTaskDetail = (row: any) => {
  ElMessage({
    message: `查看房间${row.roomNumber}的清洁任务详情`,
    type: 'info'
  })
}

// 删除清洁任务
const handleDeleteTask = (id: number) => {
  cleaningService.deleteCleaning(id).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: `删除清洁任务ID: ${id} 成功`,
        type: 'success'
      })
      // 重新获取列表
      fetchTaskList()
    }
  }).catch((error: any) => {
    console.error('删除清洁任务失败:', error)
    ElMessage.error('删除清洁任务失败')
  })
}

// 提交清洁任务表单
const handleTaskSubmit = () => {
  taskFormRef.value.validate((valid: boolean) => {
    if (valid) {
      taskLoading.value = true
      if (taskFormData.id) {
        cleaningService.updateCleaning(Number(taskFormData.id), taskFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '编辑成功',
              type: 'success'
            })
            taskDialogVisible.value = false
            fetchTaskList()
          }
        }).catch((error: any) => {
          console.error('编辑清洁任务失败:', error)
          ElMessage.error('编辑清洁任务失败')
          taskLoading.value = false
        })
      } else {
        cleaningService.createCleaning(taskFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '添加成功',
              type: 'success'
            })
            taskDialogVisible.value = false
            fetchTaskList()
          }
        }).catch((error: any) => {
          console.error('添加清洁任务失败:', error)
          ElMessage.error('添加清洁任务失败')
          taskLoading.value = false
        })
      }
    }
  })
}

// 卫生检查搜索事件
const handleInspectionSearch = () => {
  inspectionCurrentPage.value = 1
  fetchInspectionList()
}

// 卫生检查分页事件
const handleInspectionSizeChange = (size: number) => {
  inspectionPageSize.value = size
  fetchInspectionList()
}

const handleInspectionCurrentChange = (current: number) => {
  inspectionCurrentPage.value = current
  fetchInspectionList()
}

// 添加卫生检查
const handleAddInspection = () => {
  inspectionDialogTitle.value = '添加卫生检查'
  // 重置表单
  inspectionFormData.id = ''
  inspectionFormData.roomNumber = ''
  inspectionFormData.inspectionDate = ''
  inspectionFormData.inspector = ''
  inspectionFormData.score = 10
  inspectionFormData.status = '合格'
  inspectionFormData.description = ''
  if (inspectionFormRef.value) {
    inspectionFormRef.value.resetFields()
  }
  inspectionDialogVisible.value = true
}

// 编辑卫生检查
const handleEditInspection = (row: any) => {
  inspectionDialogTitle.value = '编辑卫生检查'
  // 填充表单数据
  Object.assign(inspectionFormData, row)
  inspectionDialogVisible.value = true
}

// 查看卫生检查详情
const handleViewInspectionDetail = (row: any) => {
  ElMessage({
    message: `查看房间${row.roomNumber}的卫生检查详情`,
    type: 'info'
  })
}

// 删除卫生检查
const handleDeleteInspection = (id: number) => {
  cleaningService.deleteInspection(id).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: `删除卫生检查ID: ${id} 成功`,
        type: 'success'
      })
      // 重新获取列表
      fetchInspectionList()
    }
  }).catch((error: any) => {
    console.error('删除卫生检查失败:', error)
    ElMessage.error('删除卫生检查失败')
  })
}

// 提交卫生检查表单
const handleInspectionSubmit = () => {
  inspectionFormRef.value.validate((valid: boolean) => {
    if (valid) {
      inspectionLoading.value = true
      if (inspectionFormData.id) {
        cleaningService.updateInspection(Number(inspectionFormData.id), inspectionFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '编辑成功',
              type: 'success'
            })
            inspectionDialogVisible.value = false
            fetchInspectionList()
          }
        }).catch((error: any) => {
          console.error('编辑卫生检查失败:', error)
          ElMessage.error('编辑卫生检查失败')
          inspectionLoading.value = false
        })
      } else {
        cleaningService.createInspection(inspectionFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '添加成功',
              type: 'success'
            })
            inspectionDialogVisible.value = false
            fetchInspectionList()
          }
        }).catch((error: any) => {
          console.error('添加卫生检查失败:', error)
          ElMessage.error('添加卫生检查失败')
          inspectionLoading.value = false
        })
      }
    }
  })
}
</script>

<style scoped>
.cleaning-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.add-button {
  margin-top: 5px;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  width: 100%;
  overflow-x: auto;
  margin-bottom: 16px;
  overflow: hidden;
}

 &:deep(.el-table__header-wrapper){
  overflow-x: hidden;
}



.custom-table-class:deep(.el-table__header) {
  col[name="gutter"] {
    display: table-cell !important;
  }
}
</style>